const db = require('../config/db');

// Add a new guest
exports.addGuest = async (req, res) => {
    try {
        const { name, gender, id_card, phone } = req.body;

        // Check if ID card already exists
        const [existingGuest] = await db.query(
            'SELECT * FROM Guests WHERE id_card = ?',
            [id_card]
        );

        if (existingGuest.length > 0) {
            return res.status(400).json({ error: '身份证号已存在', message: `身份证号 ${id_card} 已存在，请检查` });
        }

        const [result] = await db.query(
            'INSERT INTO Guests (name, gender, id_card, phone) VALUES (?, ?, ?, ?)',
            [name, gender, id_card, phone]
        );
        res.status(201).json({ message: '客户添加成功', guestId: result.insertId });
    } catch (err) {
        console.error('添加客户错误:', err);
        res.status(500).json({ error: '添加客户失败', details: err.message });
    }
};
// backend/controllers/guestController.js

// ... (现有所有函数，直到 exports.deleteGuest 的结束)

// Bulk import guests (新增此函数)
exports.bulkImportGuests = async (req, res) => {
    try {
        const guests = req.body; // 假设 req.body 是客户对象数组

        if (!Array.isArray(guests) || guests.length === 0) {
            return res.status(400).json({ error: '无效的数据', message: '导入数据应为非空数组。' });
        }

        // 提取所有要导入的身份证号
        const idCards = guests.map(guest => guest.id_card);

        // 检查数据库中是否已存在这些身份证号
        const [existingGuests] = await db.query(
            `SELECT id_card FROM Guests WHERE id_card IN (?)`,
            [idCards]
        );

        const existingIdCards = existingGuests.map(guest => guest.id_card);
        const duplicates = guests.filter(guest => existingIdCards.includes(guest.id_card));

        if (duplicates.length > 0) {
            const duplicateCards = duplicates.map(g => g.id_card).join(', ');
            return res.status(400).json({
                error: '存在重复身份证号',
                message: `以下身份证号已存在: ${duplicateCards}`,
                duplicates
            });
        }

        // 构建批量插入的 values
        const values = guests.map(guest => [
            guest.name,
            guest.gender,
            guest.id_card,
            guest.phone
        ]);

        const [result] = await db.query(
            'INSERT INTO Guests (name, gender, id_card, phone) VALUES ?',
            [values]
        );

        res.status(201).json({
            message: `成功导入${result.affectedRows}个客户`,
            importedCount: result.affectedRows
        });

    } catch (err) {
        if (err.code === 'ER_DUP_ENTRY') {
            console.error('批量导入客户身份证号冲突:', err);
            res.status(400).json({
                error: '存在重复身份证号',
                message: '导入文件中包含已存在的身份证号（可能是由于并发或旧数据，请检查）'
            });
        } else {
            console.error('批量导入客户错误:', err);
            res.status(500).json({ error: '批量导入客户失败', details: err.message });
        }
    }
};

// Search/Get all guests
exports.searchGuests = async (req, res) => {
    try {
        const { name, id_card } = req.query;
        let query = 'SELECT * FROM Guests WHERE 1=1';
        const params = [];

        if (name) {
            query += ' AND name LIKE ?';
            params.push(`%${name}%`);
        }
        if (id_card) {
            query += ' AND id_card LIKE ?';
            params.push(`%${id_card}%`);
        }

        const [rows] = await db.query(query, params);
        res.status(200).json(rows); // This returns an array of guests directly
    } catch (err) {
        console.error('搜索客户错误:', err);
        res.status(500).json({ error: '搜索客户失败', details: err.message });
    }
};

// Update guest information
exports.updateGuest = async (req, res) => {
    try {
        const { id } = req.params;
        const { name, gender, id_card, phone } = req.body;

        // Check if the updated ID card conflicts with other guests
        const [existingGuest] = await db.query(
            'SELECT * FROM Guests WHERE id_card = ? AND guest_id != ?',
            [id_card, id]
        );

        if (existingGuest.length > 0) {
            return res.status(400).json({ error: '身份证号已存在', message: `身份证号 ${id_card} 已被其他客户使用` });
        }

        const [result] = await db.query(
            'UPDATE Guests SET name = ?, gender = ?, id_card = ?, phone = ? WHERE guest_id = ?',
            [name, gender, id_card, phone, id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: '客户未找到' });
        }
        res.status(200).json({ message: '客户信息更新成功' });
    } catch (err) {
        console.error('更新客户错误:', err);
        res.status(500).json({ error: '更新客户失败', details: err.message });
    }
};

// Delete a guest///删除客户没有实现
exports.deleteGuest = async (req, res) => {
    try {
        const { id } = req.params;
        // Check if the guest has any active check-ins
        const [activeCheckins] = await db.query(
            'SELECT * FROM Checkins WHERE guest_id = ? AND status = "入住中"',
            [id]
        );
        if (activeCheckins.length > 0) {
            return res.status(400).json({ error: '无法删除客户', message: '该客户存在未退房的入住记录，请先办理退房。' });
        }

        // Delete related consumption records first
        await db.query('DELETE FROM Consumptions WHERE checkin_id IN (SELECT checkin_id FROM Checkins WHERE guest_id = ?)', [id]);
        // Then delete the guest's check-in records
        await db.query('DELETE FROM Checkins WHERE guest_id = ?', [id]);
        // Finally, delete the guest
        const [result] = await db.query('DELETE FROM Guests WHERE guest_id = ?', [id]);

        if (result.affectedRows === 0) {
            return res.status(404).json({ error: '客户未找到' });
        }
        res.status(200).json({ message: '客户删除成功' });
    } catch (err) {
        console.error('删除客户错误:', err);
        res.status(500).json({ error: '删除客户失败', details: err.message });
    }
};

// Get guest by ID card (for client-side)
exports.getGuestByCard = async (req, res) => {
    try {
        const { idCard } = req.params;
        const [rows] = await db.query(
            'SELECT * FROM Guests WHERE id_card = ?',
            [idCard]
        );
        if (rows.length === 0) {
            return res.status(404).json({ error: '客户未找到', message: '未找到该身份证号对应的客户信息。' });
        }
        res.status(200).json(rows[0]);
    } catch (err) {
        console.error('根据身份证查询客户错误:', err);
        res.status(500).json({ error: '查询客户失败', details: err.message });
    }
};
